package com.sfeir.android.friendapps.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.sfeir.android.friendapps.model.User;

public class AppsController {
	
	/**
	 * get User with HttpRequest
	 * @see #convertStreamToString(InputStream)
	 * @see #myJsonParser(String)
	 * @see #mySplitTab(String)
	 * @param email
	 * @param idList
	 * @return
	 */
	public User retrieveUser(String email, final String idList) {
		User user = new User();
		InputStream content = null;
		String jsonString = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet("http://friend-apps.appspot.com/rest/mail/"+email+"/listId/"+idList));
			content = response.getEntity().getContent();
		} catch (Exception e) {
			Log.i("[GET REQUEST]", "Network exception", e);
		}
		
		try {
			jsonString = convertStreamToString(content);
		} catch (IOException e) {
			Log.i("[STREAM CONVERT]", "IO exception", e);
			e.printStackTrace();
		}
		
		user = myJsonParser(jsonString);
		
		return user;
	}
	
	
	/**
	 * To convert the InputStream to String we use the Reader.read(char[]
	 * buffer) method. We iterate until the Reader return -1 which means
	 * there's no more data to read. We use the StringWriter class to
	 * produce the string.
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private String convertStreamToString(InputStream is) throws IOException {
		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}
	
	/**
	 * get the User from the result of the HttpRequest
	 * @param jsonString
	 * @return
	 */
	private User myJsonParser(final String jsonString){
		User u = null;
		int lenght = jsonString.length();
		int idIndex = jsonString.indexOf("\"id\":");
		int statusIndex = jsonString.indexOf("\"status\":");
		int listeIdIndex = jsonString.indexOf("\"listeId\":");
		int appLinkIndex = jsonString.indexOf("\"appLink\":");
		int langIndex = jsonString.indexOf("\"lang\":");
		int mailIndex = jsonString.indexOf("\"mail\":");
		int appNameIndex = jsonString.indexOf("\"appName\":");
		int appImgIndex = jsonString.indexOf("\"appImg\":");
		int lastDateIndex = jsonString.indexOf("\"lastDate\":");
		
		if(lenght > 0){
			String id = jsonString.substring(idIndex+5, statusIndex-1);
			String status = jsonString.substring(statusIndex+9, listeIdIndex-1);
			String listeId = jsonString.substring(listeIdIndex+10, appLinkIndex-1);
			String appLink = jsonString.substring(appLinkIndex+10, langIndex-1); // ARRAY...
			String lang = jsonString.substring(langIndex+7, mailIndex-1);
			String mail = jsonString.substring(mailIndex+7, appNameIndex-1);
			String appName = jsonString.substring(appNameIndex+10, appImgIndex-1); // ARRAY...
			String appImg = jsonString.substring(appImgIndex+9, lastDateIndex-1); // ARRAY...
			String lastDate = jsonString.substring(lastDateIndex+11, lenght-1);
			
			u = new User();
			u.setId(Long.valueOf(id));
			u.setStatus(myGetStringField(status));
			u.setLang(myGetStringField(lang));
			u.setLastDate(myGetLongField(lastDate));
			u.setListeId(myGetStringField(listeId));
			u.setMail(myGetStringField(mail));
			u.setAppLink(mySplitTab(appLink));
			u.setAppName(mySplitTab(appName));
			u.setAppImg(mySplitTab(appImg));
		}
		else{
			Log.i("[JSON]", "not found !");
		}
		
		return u;
	}
	
	private Long myGetLongField(final String field){
		Long ret = (long) 0.0;
		ret = Long.valueOf(field);
		return ret;
	}
	
	private String myGetStringField(final String field){
		if(!"null".equals(field)){
			return field.substring(1, field.length()-1);
		}
		return field;
	}
	
	/**
	 * Convert a Json tab to an ArrayList
	 * @param tabString
	 * @return
	 */
	private ArrayList<String> mySplitTab(final String tabString){
		ArrayList <String> myTab = new ArrayList<String>();
		
		String[] tabTmp = tabString.substring(1, tabString.length()-1).split(",");
		for(String tmp : tabTmp){
			if(tmp.endsWith(",")){
				tmp.substring(0, tmp.length()-1);
			}
			myTab.add(tmp.substring(1, tmp.length()-1));
		}
		
		return myTab;
	}
}
